package com.mall.framework.security;

/**
 * @author: zhaoyongke
 * @create: 2024-05-30 10:45
 * @description: jkjkj
 */

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 短信登录校验器
 */
public class OpenIdAuthenticationProvider implements AuthenticationProvider {

    @Resource
    @Qualifier("openIdUserDetailsService")
    private UserDetailsService userDetailsService;

    public OpenIdAuthenticationProvider( UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    /**
     * 重写 authenticate方法，实现身份验证逻辑。
     *
     * @param authentication
     * @return
     * @throws
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        OpenIdAuthenticationToken authenticationToken = (OpenIdAuthenticationToken) authentication;
        String openId = (String) authenticationToken.getPrincipal();// 获取凭证也就是用户的手机号
        // 根据手机号查询用户信息UserDetails
        UserDetails userDetails = userDetailsService.loadUserByUsername(openId);
        if (userDetails==null) {
            throw new InternalAuthenticationServiceException("用户不存在");
        }
        // 鉴权成功，返回一个拥有鉴权的 AbstractAuthenticationToken
        OpenIdAuthenticationToken openidAuthenticationToken = new OpenIdAuthenticationToken(userDetails, userDetails.getAuthorities());
        openidAuthenticationToken.setDetails(authenticationToken.getDetails());
        return openidAuthenticationToken;
    }

    /**
     * 重写supports方法，指定此 AuthenticationProvider 仅支持短信验证码身份验证。
     *
     * @param authentication
     * @return
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return OpenIdAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
